package com.lancoo.answer.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;


import com.lancoo.answer.R;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.DecimalFormatUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PcDialog implements OnClickListener, DialogInterface.OnDismissListener {

    private Context mContext;
    private AlertDialog mDialog;
    private EditText mEditText;
    private TextView mTotalScoreTv;
    // Parameter
    private double mTotalScore;
    // Result
    private OnPcEnsureListener mListener;
    private OnDimissCallback callback;

    public PcDialog(Context context) {
        mContext = context;
    }

    public void show(double score, double totalScore) {
        if (mDialog == null) {
            mDialog = new AlertDialog.Builder(mContext)
                    .setView(R.layout.ev_dialog_pc)
                    .show();
            initView();
        } else {
            mDialog.show();
        }
        mDialog.setOnDismissListener(this);


        mTotalScore = totalScore;

        if (score < 0) {
            mEditText.setText("");
        } else {
            mEditText.setText("");
            mEditText.setHint(DecimalFormatUtils.RoundToTheNearestDecimalPlace(score));
//            mEditText.setText(String.valueOf(DecimalFormatUtils.RoundToTheNearestDecimalPlace(score)));
        }
        mEditText.setSelection(mEditText.getText().length());

        String scoreText = "(总分" + DecimalFormatUtils.RoundToTheNearestDecimalPlace(totalScore) + "分)";
        mTotalScoreTv.setText(scoreText);

        mEditText.post(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(mEditText, 0);
            }
        });

        mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    mEditText.setHint(null);
                }
            }
        });

    }

    private void setInputLimit(){

        InputFilter filter = new InputFilter() {
            Pattern emoji = Pattern.compile(
                    "^[0-9.]*$",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

                Matcher emojiMatcher = emoji.matcher(source);
                if (!emojiMatcher.find()){
                    return "";
                }

                String input = source.toString();
                String hpScore = dest.toString()+input;
                if (!TextUtils.isEmpty(source)) {
                    Log.e("ccc","被触发了"+source);
                    Log.e("ccc","被触发了"+dest.toString());

                    if (dest.toString().contains(".")){
                        if (input.contains(".")){
                            return ".";
                        }
                    }
                    if ((hpScore).startsWith(".")) {
//                        ToastUtils.show(mEditText.getContext(),"请输入规范的分值！");
//                        mEditText.setText("");
                        return "";
                    }

                    if (Float.parseFloat(hpScore) > mTotalScore) {
//                        ToastUtil.show(mEditText.getContext(),"输入分值不能大于总分！");
//                        mEditText.setText("");
                        return "";
                    }

                    if (hpScore.contains(".")) {
                        String[] strings = hpScore.split("\\.");
                        if (strings.length == 2 && strings[1].length() > 1) {
//                            mEditText.setText("");
                            return "";
//                            String str = strings[0] + "." + strings[1].substring(0, 1);
//                            mEditText.setText(str);
//                            mEditText.setSelection(mEditText.getText().length());
                        }
                    }

                    if (hpScore.length()>1) {
                        String first = hpScore.substring(0,1);
                        if (first.equals("0")){
                            Log.e("ccc","进来了"+hpScore);
                            if (hpScore.contains(".")){
                                return null;
                            }else {
//                                mEditText.setText(hpScore.substring(1,hpScore.length()-1));
                                return"";
                            }
                        }
                    }


                }
                return null;
            }
        };

        mEditText.setFilters(new InputFilter[]{filter});

    }


    private void initView() {
        Window window = mDialog.getWindow();
        mEditText = (EditText) window.findViewById(R.id.et);
        mTotalScoreTv = (TextView) window.findViewById(R.id.totalScoreTv);

        mEditText.setFilters(new InputFilter[]{SoftInputUtils.getEmojiFilter()});

        window.findViewById(R.id.cancelBtn).setOnClickListener(this);
        window.findViewById(R.id.ensureBtn).setOnClickListener(this);
        setListener();
    }

    private void setListener() {

        setInputLimit();
//        mEditText.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                String hpScore = s.toString();
//                if (!TextUtils.isEmpty(hpScore)) {
//                    Log.e("ccc","被触发了"+hpScore);
//                    if (hpScore.startsWith(".")) {
//                        ToastUtil.show(mEditText.getContext(),"请输入规范的分值！");
//                        mEditText.setText("");
//                        return;
//                    }
//
//                    if (Float.parseFloat(hpScore) > mTotalScore) {
//                        ToastUtil.show(mEditText.getContext(),"输入分值不能大于总分！");
//                        mEditText.setText("");
//                        return;
//                    }
//
//                    if (hpScore.length()>1) {
//                        String first = hpScore.substring(0,1);
//                        if (first.equals("0")){
//                            Log.e("ccc","进来了"+hpScore);
//                            if (hpScore.contains(".")){
//
//                            }else {
//                                mEditText.setText(hpScore.substring(1,hpScore.length()-1));
//                                return;
//                            }
//
//
//                        }
//                    }
//
//                    if (hpScore.contains(".")) {
//                        String[] strings = hpScore.split("\\.");
//                        if (strings.length == 2 && strings[1].length() > 1) {
//                            mEditText.setText("");
////                            String str = strings[0] + "." + strings[1].substring(0, 1);
////                            mEditText.setText(str);
////                            mEditText.setSelection(mEditText.getText().length());
//                        }
//                    }
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//            }
//        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ensureBtn) {
            if (mListener != null) {
                String hpScore = mEditText.getText().toString();
                if (!TextUtils.isEmpty(hpScore)) {
                    float score = Float.parseFloat(hpScore);
                    if (score <= mTotalScore) {
                        mListener.onPcEnsure(score);
                    }
                }
            }
        }
        mDialog.dismiss();
    }

    @Override
    public void onDismiss(DialogInterface dialogInterface) {
        Log.e("aaa","评分弹窗关闭了@!!!");
        if (callback!=null){
            callback.ondimissCallback();
        }
        if (mEditText!=null){
            mEditText.clearFocus();
        }

    }

    public interface OnPcEnsureListener {
        void onPcEnsure(float score);
    }

    public interface OnDimissCallback {
        void ondimissCallback();
    }

    public void setDimissCallback(OnDimissCallback callback){
        this.callback = callback;
    }

    public void setOnPcEnsureListener(OnPcEnsureListener listener) {
        mListener = listener;
    }

    public void relase(){

        mContext = null;
        callback = null;
        mListener = null;
        if (mDialog!=null){
            mDialog.dismiss();
            mDialog = null;
        }
    }
}
